package com.service.api;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.service.other.Logger;
import com.service.bean.company.Company;
import com.service.bean.device.Vehicle;
import com.service.bean.signal.GpsSignal;
import com.service.cache.CacheManager;
import com.service.db.DbManager;

public class BaiduApiLocation extends BaiduApiServer {

	private GpsSignal bean;
	
	private List<GpsSignal> beans;
	
	public BaiduApiLocation() {
		
	}

	@Override
	public void run() {
		for (Vehicle vehicle : CacheManager.instance().getAllVehicle()) {
			Api_Location(vehicle.company);
		}
	}

	@Override
	public void callBack(String json) {
		String status = null;
		try {
			Pattern p = Pattern.compile("\"status\":\"?(?<status>\\S+?)\"?");
			Matcher m = p.matcher(json);
			if (m.find()) {
				status = m.group("status");
				if ("0".equals(status)) {
					this.bean.isLocation = 1;
					this.bean.isPosition = 1;
					p = Pattern.compile("\"formatted_address\":\"(?<address>\\S+?)\"");
					m = p.matcher(json);
					if(m.find()){
						this.bean.baiduLocation = m.group("address");
					}
					p = Pattern.compile("\"street\":\"(?<street>\\S+?)\"");
					m = p.matcher(json);
					if(m.find()){
						this.bean.baiduStreet = m.group("street");
					}
				}
			}
		} catch (Exception e) {
			Logger.err(e);
		}
		if (beans.get(beans.size() - 1).signalId.equals(this.bean.signalId)) {
			Vehicle v = CacheManager.instance().getVehicle(beans.get(0).gpsNo);
			DbManager.instance().dbs.updateGpsList(beans,v.company);
		}
	}

	private void Api_Location(Company company) {
		try {
			beans = DbManager.instance().dbs.getNotLocationGps(company);
			for (GpsSignal b : beans) {
				this.bean = b;
				StringBuilder builder = new StringBuilder();
				builder.append("http://api.map.baidu.com/geocoder/v2/?");
				builder.append("ak=x2QVIn5dDgDC7wRZ6WGoQykb");
				builder.append("&coordtype=bd09ll");
				builder.append("&pois=0");
				builder.append("&output=json");
				builder.append("&location=");
				builder.append(String.valueOf(b.baiduLat));
				builder.append(",");
				builder.append(String.valueOf(b.baiduLng));
				HttpClient client = new HttpClient();
				client.doRequest(builder.toString(), this);
			}
		} catch (Exception e) {
			Logger.err(e);
		}
	}
}
